<template>
  <div class="h-full flex flex-col relative">
    <!-- 固定通知区域 -->
    <div v-if="showNotification" class="absolute top-0 left-0 right-0 z-10 p-3 rounded-lg border-l-4 shadow-lg transition-all duration-300 transform animate-slide-down"
         :class="{
           'bg-orange-50 border-orange-400 text-orange-700': notificationType === 'warning',
           'bg-green-50 border-green-400 text-green-700': notificationType === 'success',
           'bg-blue-50 border-blue-400 text-blue-700': notificationType === 'info',
           'bg-red-50 border-red-400 text-red-700': notificationType === 'error'
         }">
      <div class="flex items-center">
        <svg v-if="notificationType === 'warning'" class="w-5 h-5 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
        </svg>
        <svg v-else-if="notificationType === 'success'" class="w-5 h-5 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
        </svg>
        <svg v-else-if="notificationType === 'error'" class="w-5 h-5 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
        </svg>
        <svg v-else class="w-5 h-5 mr-2 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
          <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"></path>
        </svg>
        <span class="text-sm font-medium">{{ notificationMessage }}</span>
        <button @click="showNotification = false" class="ml-auto text-current opacity-70 hover:opacity-100">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
          </svg>
        </button>
      </div>
    </div>

    <!-- 标题区域 -->
    <div class="mb-4">
      <h2 class="text-lg font-semibold text-gray-900 mb-1">图片上传</h2>
      <p class="text-sm text-gray-600">选择或拖拽图片到下方区域</p>
    </div>

    <!-- 上传区域 - 固定高度，内部可滚动 -->
    <div class="flex-1 flex flex-col min-h-0">
      <div 
        class="upload-area border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer transition-all duration-300 hover:border-green-400 hover:bg-green-50 flex-1 flex flex-col overflow-y-auto"
        :class="{ 
          'border-green-400 bg-green-50': isDragOver,
          'border-blue-400 bg-blue-50': selectedImages.length > 0
        }"
        @click="triggerFileUpload"
        @dragover.prevent="handleDragOver"
        @dragleave.prevent="handleDragLeave"
        @drop.prevent="handleDrop"
      >
        <div v-if="selectedImages.length === 0" class="space-y-4">
          <div class="w-16 h-16 bg-gradient-to-r from-green-500 to-emerald-500 rounded-xl flex items-center justify-center mx-auto">
            <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
            </svg>
          </div>
          <div>
            <h3 class="text-lg font-semibold text-gray-900 mb-2">批量上传图片</h3>
            <p class="text-gray-600 mb-1">点击或拖拽多张图片到此处</p>
            <p class="text-xs text-gray-500">支持 JPG、PNG 格式，最多20张，每张最大10MB</p>
          </div>
        </div>
        
        <div v-else class="space-y-4">
          <!-- 图片预览列表 - 每行一张图片 -->
          <div class="space-y-3">
            <div 
              v-for="(image, index) in selectedImages" 
              :key="index" 
              class="relative group"
            >
              <!-- 主图片显示 -->
              <img 
                :src="image.url" 
                :alt="`图片 ${index + 1}`" 
                class="w-full h-32 object-cover rounded-lg shadow-md transition-all duration-200 hover:shadow-lg"
                :class="{ 
                  'opacity-50 grayscale': image.isDuplicate,
                  'ring-2 ring-green-400': image.isUploaded && !image.isDuplicate,
                  'ring-2 ring-orange-400': image.isDuplicate
                }"
              />
              
              <!-- 重复检测标记 -->
              <div v-if="image.isDuplicate" class="absolute top-2 left-2">
                <span class="px-2 py-1 bg-orange-500 text-white text-xs rounded-full font-medium shadow-md">
                  重复
                </span>
              </div>
              
              <!-- 上传完成标记 -->
              <div v-if="image.isUploaded" class="absolute top-2 right-2">
                <span class="px-2 py-1 bg-green-500 text-white text-xs rounded-full font-medium shadow-md">
                  已上传
                </span>
              </div>
              
              <!-- 删除按钮 -->
              <button 
                @click.stop="removeImage(index)" 
                class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600 shadow-md"
                :class="{ 'top-8': image.isUploaded }"
              >
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
              
              <!-- 文件名和大小信息 -->
              <div class="absolute bottom-0 left-0 right-0 bg-black bg-opacity-70 text-white text-xs p-2 rounded-b-lg">
                <div class="truncate font-medium">{{ image.name }}</div>
                <div class="text-xs opacity-75 mt-1">
                  {{ Math.round(image.file.size / 1024) }}KB
                </div>
              </div>
            </div>
          </div>
          
          <div class="text-center space-y-1">
            <p class="text-sm text-gray-600">
              已选择 <span class="font-semibold text-blue-600">{{ selectedImages.length }}</span> 张图片
            </p>
            <div v-if="duplicateCount > 0" class="text-xs text-orange-600">
              包含 <span class="font-semibold">{{ duplicateCount }}</span> 张重复图片
            </div>
            <div v-if="uploadedCount > 0" class="text-xs text-green-600">
              已上传 <span class="font-semibold">{{ uploadedCount }}</span> 张图片
            </div>
          </div>
        </div>
      </div>
      
      <input 
        ref="fileInput"
        type="file" 
        accept="image/*" 
        multiple
        @change="handleFileSelect"
        class="hidden"
      />
      
      <!-- 操作按钮 -->
      <div class="flex flex-col gap-3 mt-4">
        <button 
          @click="triggerFileUpload" 
          class="btn btn-secondary text-sm py-2"
        >
          <svg class="w-4 h-4 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
          </svg>
          <span>{{ selectedImages.length > 0 ? '添加更多图片' : '选择图片' }}</span>
        </button>
        <button 
          @click="$emit('analyze', selectedImages)" 
          :disabled="selectedImages.length === 0 || isAnalyzing"
          class="btn btn-primary text-sm py-2"
          :class="{ 'opacity-50 cursor-not-allowed': selectedImages.length === 0 || isAnalyzing }"
        >
          <svg v-if="isAnalyzing" class="w-4 h-4 mr-2 flex-shrink-0 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          <svg v-else class="w-4 h-4 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
          </svg>
          <span>{{ isAnalyzing ? `分析中... (${currentAnalyzingIndex + 1}/${selectedImages.length})` : '开始批量分析' }}</span>
        </button>
        <button 
          v-if="selectedImages.length > 0"
          @click="clearAllImages" 
          class="btn btn-danger text-sm py-2"
        >
          <svg class="w-4 h-4 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
          </svg>
          <span>清空所有</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  isAnalyzing: {
    type: Boolean,
    default: false
  },
  currentAnalyzingIndex: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['analyze', 'update:selectedImages'])

const selectedImages = ref([])
const isDragOver = ref(false)
const fileInput = ref(null)
const showNotification = ref(false)
const notificationMessage = ref('')
const notificationType = ref('info')

// 计算属性：重复图片数量
const duplicateCount = computed(() => {
  return selectedImages.value.filter(img => img.isDuplicate).length
})

// 计算属性：已上传图片数量
const uploadedCount = computed(() => {
  return selectedImages.value.filter(img => img.isUploaded).length
})


const triggerFileUpload = () => {
  fileInput.value.click()
}

const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  processFiles(files)
}

const handleDragOver = (event) => {
  isDragOver.value = true
}

const handleDragLeave = (event) => {
  isDragOver.value = false
}

const handleDrop = (event) => {
  isDragOver.value = false
  const files = Array.from(event.dataTransfer.files)
  processFiles(files)
}

// 检测文件名重复
const checkDuplicate = (filename) => {
  return selectedImages.value.some(img => img.name === filename)
}

// 标记图片为已上传
const markAsUploaded = (filename) => {
  const image = selectedImages.value.find(img => img.name === filename)
  if (image) {
    image.isUploaded = true
    emit('update:selectedImages', selectedImages.value)
    
    // 显示上传成功通知
    showUploadSuccessNotification(filename)
  }
}

// 显示上传成功通知
const showUploadSuccessNotification = (filename) => {
  notificationMessage.value = `图片 "${filename}" 上传完成`
  notificationType.value = 'success'
  showNotification.value = true
  
  // 2秒后自动隐藏通知
  setTimeout(() => {
    showNotification.value = false
  }, 2000)
}

// 批量标记图片为已上传
const markBatchAsUploaded = (filenames) => {
  filenames.forEach(filename => {
    const image = selectedImages.value.find(img => img.name === filename)
    if (image) {
      image.isUploaded = true
    }
  })
  emit('update:selectedImages', selectedImages.value)
  
  // 显示批量上传完成通知
  if (filenames.length > 0) {
    notificationMessage.value = `批量上传完成，共 ${filenames.length} 张图片`
    notificationType.value = 'success'
    showNotification.value = true
    
    setTimeout(() => {
      showNotification.value = false
    }, 3000)
  }
}

// 显示通知
const showDuplicateNotification = (duplicateFiles) => {
  notificationMessage.value = `跳过 ${duplicateFiles.length} 个重复文件：${duplicateFiles.slice(0, 3).join(', ')}${duplicateFiles.length > 3 ? '...' : ''}`
  notificationType.value = 'warning'
  showNotification.value = true
  
  // 3秒后自动隐藏通知
  setTimeout(() => {
    showNotification.value = false
  }, 3000)
}

const processFiles = (files) => {
  const imageFiles = files.filter(file => file.type.startsWith('image/'))
  
  if (imageFiles.length === 0) {
    showErrorNotification('请选择有效的图片文件')
    return
  }
  
  if (selectedImages.value.length + imageFiles.length > 20) {
    showErrorNotification('最多只能选择20张图片')
    return
  }
  
  let duplicateFiles = []
  let oversizedFiles = []
  let validFiles = []
  
  // 分离重复文件、超大文件和有效文件
  imageFiles.forEach(file => {
    if (file.size > 10 * 1024 * 1024) {
      oversizedFiles.push(file.name)
      return
    }
    
    if (checkDuplicate(file.name)) {
      duplicateFiles.push(file.name)
    } else {
      validFiles.push(file)
    }
  })
  
  // 显示各种提示
  if (oversizedFiles.length > 0) {
    showErrorNotification(`以下文件超过10MB限制：${oversizedFiles.slice(0, 2).join(', ')}${oversizedFiles.length > 2 ? '...' : ''}`)
  }
  
  if (duplicateFiles.length > 0) {
    showDuplicateNotification(duplicateFiles)
  }
  
  if (validFiles.length === 0) {
    return
  }
  
  // 处理有效文件
  if (validFiles.length > 0) {
    validFiles.forEach(file => {
      const reader = new FileReader()
      reader.onload = (e) => {
        selectedImages.value.push({
          name: file.name,
          url: e.target.result,
          file: file,
          isDuplicate: false,
          isUploaded: false
        })
        emit('update:selectedImages', selectedImages.value)
      }
      reader.onerror = () => {
        showErrorNotification(`文件 "${file.name}" 读取失败`)
      }
      reader.readAsDataURL(file)
    })
  }
}

// 显示错误通知
const showErrorNotification = (message) => {
  notificationMessage.value = message
  notificationType.value = 'error'
  showNotification.value = true
  
  setTimeout(() => {
    showNotification.value = false
  }, 4000)
}

const removeImage = (index) => {
  selectedImages.value.splice(index, 1)
  emit('update:selectedImages', selectedImages.value)
}

const clearAllImages = () => {
  selectedImages.value = []
  emit('update:selectedImages', selectedImages.value)
  fileInput.value.value = ''
}

// 暴露方法给父组件
defineExpose({
  markAsUploaded,
  markBatchAsUploaded,
  selectedImages
})
</script>
